﻿using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;

namespace System.Web.Mvc
{
	public static partial class Holovacs
	{
		public static HtmlString DescriptionFor<TModel, TProperty>(
		this HtmlHelper<TModel> htmlHelper,
		Expression<Func<TModel, TProperty>> expression) where TModel : class
		{
			//initialize values
			var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
			var propertyName = metaData.PropertyName;
			var propertyValue = htmlHelper.ViewData.Eval(propertyName).ToStringOrEmpty();
			var displayAttribute = ((DisplayAttribute[])metaData.GetType().GetCustomAttributes(
				typeof(DisplayAttribute), false)).FirstOrDefault();

			//collect the display description attribute, if it exists
			var displayText = string.Empty;
			if (displayAttribute != null)
			{
				displayText = HttpUtility.HtmlEncode(displayAttribute.Description.ToStringOrEmpty());
			}

			return new HtmlString(displayText);
		}
	}
}
